package com.raising.framework.filter;

import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 特殊符号过滤，防止sql注入以及其他恶意代码
 * @author gaoy
 * 2017 2017-5-7 下午6:43:53
 */
public class XssFilter implements Filter {  
      
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {  
    }  
  
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,  
            FilterChain chain) throws IOException, ServletException {
    	HttpServletRequest request = (HttpServletRequest) servletRequest;
    	HttpServletResponse response = ((HttpServletResponse) servletResponse);
    	//只有富文本编辑框的特殊字符可以提交 @author gaoy
    	if(request.getRequestURI().indexOf("cms/article/create")>-1||request.getRequestURI().indexOf("cms/article/update")>-1
    			||request.getRequestURI().indexOf("res/product/create")>-1||request.getRequestURI().indexOf("res/product/update")>-1
    			||request.getRequestURI().indexOf("res/project/create")>-1||request.getRequestURI().indexOf("res/project/update")>-1
                ||request.getRequestURI().indexOf("workflow/process/deployXml")>-1
                ||request.getRequestURI().indexOf("code/codeTemplate/update.json")>-1){
    		chain.doFilter(request, response);
    	}else{
    		chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
    	}
    }  
  
    @Override
    public void destroy() {  
    }  
    
    class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {  
    	  
        public XssHttpServletRequestWrapper(HttpServletRequest request) {  
            super(request);  
        }  
      
        @Override  
        public String getHeader(String name) {  
            return StringEscapeUtils.escapeHtml4(super.getHeader(name));  
        }  
      
        @Override  
        public String getQueryString() {  
            return StringEscapeUtils.escapeHtml4(super.getQueryString());  
        }  
      
        @Override  
        public String getParameter(String name) {  
            return StringEscapeUtils.escapeHtml4(super.getParameter(name));  
        }  
      
        @Override  
        public String[] getParameterValues(String name) {  
            String[] values = super.getParameterValues(name);  
            if(values != null) {  
                int length = values.length;  
                String[] escapseValues = new String[length];  
                for(int i = 0; i < length; i++){  
                    escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]);  
                }
                return escapseValues;
            }
            return super.getParameterValues(name);  
        }
    }
}